package com.siyoumi.console.modules.sys.interceptor;

import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.InputData;
import com.siyoumi.config.SysConfig;
import com.siyoumi.console.config.CmdConfig;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.interceptor.InterceptorBase;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ConsoleInterceptor
        extends InterceptorBase
        implements HandlerInterceptor {
    /**
     * 执行前
     *
     * @return boolean
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        XLog.info(this.getClass(), "BEGIN");

        //权限验证
        InputData inputData = InputData.fromRequest();
        String token = inputData.input("token");
        if (XStr.isNullOrEmpty(token)) {
            XValidator.err(EnumSys.TOKEN_MISS.getR());
        }

        CmdConfig config = CmdConfig.getIns();
        if (token.equals(config.getLongToken())) {
            //长期token
            return true;
        }

        token = "console:" + token;
        String tokenVal = XRedis.getBean().get(token);
        if (XStr.isNullOrEmpty(tokenVal)) {
            XValidator.err(EnumSys.TOKEN_ERR.getR());
        }
        if (!SysConfig.getIns().isServer(tokenVal)) {
            XValidator.err(EnumSys.TOKEN_ERR.getR("token 异常"));
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        XLog.info(this.getClass(), "END");
    }
}
